# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class BSTIterator:

    def __init__(self, root: TreeNode):
        self.stk = []
        self.BSTIterator(root)


    def pushLeftBranch(self, p):
        while p:
            self.stk.append(p)
            p = p.left
    
    def BSTIterator(self, root):
        self.pushLeftBranch(root)


    def next(self) -> int:
        p = self.stk.pop()
        self.pushLeftBranch(p.right)
        return p.val


    def hasNext(self) -> bool:
        return len(self.stk)!=0